import { createStore } from 'vuex';
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo } from '@/utils/auth';
import { login, register, getUserInfo as fetchUserInfo, logout } from '@/api/auth';
import { ElMessage } from 'element-plus';

const store = createStore({
  state() {
    // 先尝试从localStorage获取用户信息，确保初始状态有数据
    const savedUserInfo = getUserInfo();
    return {
      token: getToken(),
      userInfo: savedUserInfo,
      roles: savedUserInfo?.roles || [],
      permissions: savedUserInfo?.permissions || []
    };
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token;
    },
    SET_USER_INFO(state, userInfo) {
      console.log('[Store/SET_USER_INFO] 设置用户信息:', userInfo);
      state.userInfo = userInfo;
      
      // 处理角色数据
      if (userInfo && userInfo.roles) {
        console.log('[Store/SET_USER_INFO] 设置角色:', userInfo.roles);
        state.roles = Array.isArray(userInfo.roles) ? userInfo.roles : [];
      } else {
        state.roles = [];
      }
      
      // 处理权限数据
      if (userInfo && userInfo.permissions) {
        console.log('[Store/SET_USER_INFO] 设置权限:', userInfo.permissions);
        state.permissions = Array.isArray(userInfo.permissions) ? userInfo.permissions : [];
        // 确认权限有效性
        console.log('[Store/SET_USER_INFO] 权限数组长度:', state.permissions.length);
        console.log('[Store/SET_USER_INFO] 权限数组类型:', typeof state.permissions);
        console.log('[Store/SET_USER_INFO] 是否包含graph:view:', state.permissions.includes('graph:view'));
      } else {
        state.permissions = [];
      }
    },
    // 单独更新权限的mutation
    SET_PERMISSIONS(state, permissions) {
      if (permissions && Array.isArray(permissions)) {
        console.log('[Store/SET_PERMISSIONS] 直接设置权限:', permissions);
        state.permissions = permissions;
      }
    }
  },
  actions: {
    // 用户登录
    login({ commit, dispatch }, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password })
          .then(response => {
            const { token } = response;
            commit('SET_TOKEN', token);
            setToken(token);
            
            // 登录成功后立即获取用户信息
            dispatch('getUserInfo')
              .then(() => {
                resolve();
              })
              .catch(error => {
                reject(error);
              });
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    
    // 用户注册
    register(_, userInfo) {
      return new Promise((resolve, reject) => {
        register(userInfo)
          .then(response => {
            ElMessage.success('注册成功，请登录');
            resolve(response);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    
    // 获取用户信息
    getUserInfo({ commit, state }, forceRefresh = false) {
      return new Promise((resolve, reject) => {
        if (!state.token) {
          reject(new Error('无效的令牌，请重新登录'));
          return;
        }
        
        console.log('[Store] 开始获取用户信息, forceRefresh =', forceRefresh);
        
        fetchUserInfo(forceRefresh)
          .then(response => {
            if (!response) {
              console.error('[Store] 获取用户信息失败: 响应为空');
              reject(new Error('验证失败，请重新登录'));
              return;
            }
            
            console.log('[Store] 获取用户信息成功:', response);
            console.log('[Store] 用户权限列表:', response.permissions);
            
            commit('SET_USER_INFO', response);
            setUserInfo(response);
            
            // 验证设置后的数据
            console.log('[Store] 更新后的状态: permissions =', state.permissions);
            console.log('[Store] 用户是否有graph:view权限:', state.permissions.includes('graph:view'));
            console.log('[Store] 用户是否有analysis权限:', state.permissions.some(p => p.startsWith('analysis:')));
            
            resolve(response);
          })
          .catch(error => {
            console.error('[Store] 获取用户信息失败:', error);
            reject(error);
          });
      });
    },
    
    // 用户登出
    logout({ commit }) {
      return new Promise((resolve) => {
        // 首先清除本地数据，不等待API响应
        console.log('清除本地登录状态...');
        commit('SET_TOKEN', null);
        commit('SET_USER_INFO', null);
        removeToken();
        removeUserInfo();
        localStorage.removeItem('vuex');
        sessionStorage.clear();

        // 然后尝试调用登出API
        console.log('正在调用登出API...');
        logout()
          .then(response => {
            console.log('登出API响应成功:', response);
            resolve(response);
          })
          .catch(error => {
            // 即使API调用失败，也不影响前端登出逻辑
            console.error('登出API调用失败，但不影响前端登出:', error);
            resolve();
          });
      });
    },
    
    // 重置令牌
    resetToken({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', null);
        commit('SET_USER_INFO', null);
        removeToken();
        removeUserInfo();
        resolve();
      });
    }
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    roles: state => state.roles,
    permissions: state => state.permissions,
    hasRole: state => role => {
      if (!state.roles || state.roles.length === 0) {
        return false;
      }
      if (Array.isArray(role)) {
        return role.some(r => state.roles.includes(r));
      }
      return state.roles.includes(role);
    },
    hasPermission: state => permission => {
      if (!state.permissions || state.permissions.length === 0) {
        return false;
      }
      if (Array.isArray(permission)) {
        return permission.some(p => state.permissions.includes(p));
      }
      return state.permissions.includes(permission);
    },
    hasAnyGraphPermission: state => {
      // 打印原始权限数据
      console.log('[Store/hasAnyGraphPermission] 原始权限数据类型:', typeof state.permissions, '是否是数组:', Array.isArray(state.permissions));
      console.log('[Store/hasAnyGraphPermission] 原始权限数据:', state.permissions);
      
      // 明确判断权限数组是否为空
      if (!state.permissions || !Array.isArray(state.permissions) || state.permissions.length === 0) {
        console.log('[Store/hasAnyGraphPermission] 没有任何权限');
        return false;
      }
      
      // 检查是否有图谱基础权限
      const hasGraphView = state.permissions.includes('graph:view');
      console.log('[Store/hasAnyGraphPermission] 是否有graph:view权限:', hasGraphView);
      
      if (hasGraphView) {
        console.log('[Store/hasAnyGraphPermission] 用户有graph:view权限，返回true');
        return true;
      }
      
      // 检查是否有任何分析相关权限
      const analysisPermissions = state.permissions.filter(p => p && typeof p === 'string' && p.startsWith('analysis:'));
      console.log('[Store/hasAnyGraphPermission] 分析类权限:', analysisPermissions);
      const hasAnalysis = analysisPermissions.length > 0;
      console.log('[Store/hasAnyGraphPermission] 是否有分析权限:', hasAnalysis);
      
      return hasAnalysis;
    }
  }
});

export default store; 